package com.kaigejava.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author kaigejava
 * 带有版本号atomic类解决ABA问题
 *
 */
public class ABAStempDemo {
    static  AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(127,1);
    public static void main(String[] args) {
           new Thread(()->{
               int tamp = atomicStampedReference.getStamp();
               System.out.println("A线程内主内存中的值为:"+atomicStampedReference.getReference()
                       +"\t 当前版本号为:"+tamp);
               try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { }
               System.out.println("A线程执行一次操作后的版本号："+
                       atomicStampedReference.compareAndSet(127,15,atomicStampedReference.getStamp(),
                               atomicStampedReference.getStamp()+1)+" \t"+atomicStampedReference.getStamp());
               System.out.println("A线程执行第二次操作后的值："
                       +atomicStampedReference.compareAndSet(15,127,
                       atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1)+"\t"+atomicStampedReference.getStamp());

           },"线程A").start();
        //线程2睡上1s.等等下线程A执行一次ABA
        System.out.println("=======================线程2=================================");
        new Thread(()->{
            int tamp = atomicStampedReference.getStamp();
            System.out.println("线程2内主内存中的值为:"+atomicStampedReference.getReference()+"\t 版本号为:"+tamp);
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { }

            System.out.println(atomicStampedReference.compareAndSet(127,11,tamp,tamp+1)
            +"线程2执行一次操作后的值："+atomicStampedReference.getReference()
                    +"\t 当前主内存中的版本号为："+atomicStampedReference.getStamp());
        },"线程2").start();
    }
}
